const std = @import("std");
const memory = @import("memory.zig");
const cpu = @import("cpu.zig");
const trap = @import("trap.zig");
const caps = @import("caps.zig");
const driver_manager = @import("driver_manager.zig");

// 能力ID类型
pub const CapabilityId = u64;

// 物理地址类型
pub const PhysicalAddress = u64;

// 虚拟地址类型
pub const VirtualAddress = u64;

// 资源类型枚举
pub const ResourceType = enum(u8) {
    memory = 1,
    cpu = 2,
    io = 3,
    interrupt = 4,
};

// 内存权限枚举
pub const MemoryPermissions = packed struct {
    read: bool = false,
    write: bool = false,
    execute: bool = false,
    _reserved: u61 = 0,
};

// API函数：获取能力
// 这是exokernel的核心API之一，服务层通过能力来访问资源
export fn exokernel_get_capability(cap_id: CapabilityId) bool {
    return caps.global_capability_manager.acquireCapability(cap_id);
}

// API函数：释放能力
export fn exokernel_release_capability(cap_id: CapabilityId) void {
    caps.global_capability_manager.releaseCapability(cap_id);
}

// API函数：分配物理内存
export fn exokernel_allocate_physical_memory(
    cap_id: CapabilityId,
    size: u64,
    alignment: u64,
) PhysicalAddress {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return 0;
    }
    return memory.global_memory_manager.allocatePhysicalMemory(size, alignment) orelse 0;
}

// API函数：释放物理内存
export fn exokernel_free_physical_memory(
    cap_id: CapabilityId,
    addr: PhysicalAddress,
    size: u64,
) bool {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return false;
    }
    return memory.global_memory_manager.freePhysicalMemory(addr, size);
}

// API函数：映射虚拟内存
export fn exokernel_map_memory(
    cap_id: CapabilityId,
    virt_addr: VirtualAddress,
    phys_addr: PhysicalAddress,
    size: u64,
    perms: MemoryPermissions,
) bool {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return false;
    }
    memory.global_memory_manager.mapMemory(virt_addr, phys_addr, size, perms) catch return false;
    return true;
}

// API函数：解除内存映射
export fn exokernel_unmap_memory(
    cap_id: CapabilityId,
    virt_addr: VirtualAddress,
    size: u64,
) bool {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return false;
    }
    memory.global_memory_manager.unmapMemory(virt_addr, size) catch return false;
    return true;
}

// API函数：设置中断处理程序
export fn exokernel_set_interrupt_handler(
    cap_id: CapabilityId,
    irq: u32,
    handler: u64,
) bool {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .interrupt, .write)) {
        return false;
    }
    return trap.global_trap_handler.setInterruptHandler(irq, handler) catch false;
}

// API函数：触发中断
export fn exokernel_trigger_interrupt(
    cap_id: CapabilityId,
    irq: u32,
) bool {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .interrupt, .write)) {
        return false;
    }
    return trap.global_trap_handler.triggerInterrupt(irq) catch false;
}

// API函数：获取CPU时间片
export fn exokernel_get_cpu_time_slice(
    cap_id: CapabilityId,
    milliseconds: u32,
) bool {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .cpu, .write)) {
        return false;
    }
    return cpu.global_cpu_manager.allocateTimeSlice(milliseconds);
}

// API函数：IO端口读取
export fn exokernel_inb(cap_id: CapabilityId, port: u16) u8 {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .io, .read)) {
        return 0;
    }
    return cpu.CpuManager.inb(port);
}

// API函数：IO端口写入
export fn exokernel_outb(cap_id: CapabilityId, port: u16, value: u8) void {
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .io, .write)) {
        return;
    }
    cpu.CpuManager.outb(port, value);
}

// API函数：获取服务层初始能力
// 这是服务层启动时获取初始资源访问权限的入口点
export fn exokernel_get_initial_capabilities(
    out_mem_cap: *CapabilityId,
    out_cpu_cap: *CapabilityId,
) bool {
    return caps.global_capability_manager.getServiceLayerCapabilities(out_mem_cap, out_cpu_cap);
}

// 图形相关API函数
// 这些函数需要包含在api.zig中

// GPU资源类型
pub const GpuResourceType = enum(u8) {
    buffer = 1,
    texture = 2,
    shader = 3,
    pipeline = 4,
    command_buffer = 5,
};

// GPU队列类型
pub const GpuQueueType = enum(u8) {
    graphics = 1,
    compute = 2,
    transfer = 3,
};

// GPU资源ID
pub const GpuResourceId = u64;

// 显示设备ID
pub const DisplayDeviceId = u64;

// 显示模式结构体
pub const DisplayMode = struct {
    width: u32,
    height: u32,
    refresh_rate: u32,
    pixel_format: u32,
    pitch: u32,
};

// 驱动相关API定义

// 总线类型枚举
pub const BusType = driver_manager.BusType;

// 设备状态枚举
pub const DeviceState = driver_manager.DeviceState;

// 设备信息结构
pub const DeviceInfo = driver_manager.DeviceInfo;

// 驱动接口结构
pub const DriverInterface = driver_manager.DriverInterface;

// 设备实例结构
pub const Device = driver_manager.Device;

// GPU缓冲区描述 - 使用 gpu.zig 中的定义
pub const GpuBufferDesc = @import("gpu.zig").GpuBufferDesc;

// GPU纹理描述 - 使用 gpu.zig 中的定义
pub const GpuTextureDesc = @import("gpu.zig").GpuTextureDesc;

// 驱动管理器相关函数在 driver_manager.zig 中实现，这里只声明类型

// API函数：初始化GPU管理器
export fn exokernel_gpu_init() bool {
    const gpu = @import("gpu.zig");
    if (!gpu.global_gpu_manager.initialized) {
        var gpa = std.heap.GeneralPurposeAllocator(.{}){};
        const allocator = gpa.allocator();
        defer _ = gpa.deinit();
        
        gpu.global_gpu_manager = gpu.GpuManager.init(allocator) catch return false;
        return true;
    }
    return true;
}

// API函数：分配GPU资源
export fn exokernel_gpu_allocate_resource(
    cap_id: CapabilityId,
    resource_type: GpuResourceType,
    size: u64,
    usage: u32
) GpuResourceId {
    const gpu = @import("gpu.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return 0;
    }
    return gpu.global_gpu_manager.allocateResource(@as(gpu.GpuResourceType, @enumFromInt(@intFromEnum(resource_type))), size, usage) orelse 0;
}

// API函数：释放GPU资源
export fn exokernel_gpu_free_resource(
    cap_id: CapabilityId,
    resource_id: GpuResourceId
) bool {
    const gpu = @import("gpu.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return false;
    }
    return gpu.global_gpu_manager.freeResource(resource_id);
}

// API函数：创建GPU缓冲区
export fn exokernel_gpu_create_buffer(
    cap_id: CapabilityId,
    desc: *const GpuBufferDesc
) GpuResourceId {
    const gpu = @import("gpu.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return 0;
    }
    return gpu.global_gpu_manager.createBuffer(desc.*) orelse 0;
}

// API函数：创建GPU纹理
export fn exokernel_gpu_create_texture(
    cap_id: CapabilityId,
    desc: *const GpuTextureDesc
) GpuResourceId {
    const gpu = @import("gpu.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return 0;
    }
    return gpu.global_gpu_manager.createTexture(desc.*) orelse 0;
}

// API函数：映射GPU资源
export fn exokernel_gpu_map_resource(
    cap_id: CapabilityId,
    resource_id: GpuResourceId
) VirtualAddress {
    const gpu = @import("gpu.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .read)) {
        return 0;
    }
    return gpu.global_gpu_manager.mapResource(resource_id) orelse 0;
}

// API函数：解除GPU资源映射
export fn exokernel_gpu_unmap_resource(
    cap_id: CapabilityId,
    resource_id: GpuResourceId
) void {
    const gpu = @import("gpu.zig");
    if (caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .read)) {
        gpu.global_gpu_manager.unmapResource(resource_id);
    }
}

// API函数：提交命令缓冲区
export fn exokernel_gpu_submit_command_buffer(
    cap_id: CapabilityId,
    queue_id: u32,
    command_buffer_id: GpuResourceId
) bool {
    const gpu = @import("gpu.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .io, .write)) {
        return false;
    }
    return gpu.global_gpu_manager.submitCommandBuffer(queue_id, command_buffer_id);
}

// API函数：初始化显示管理器
export fn exokernel_display_init() bool {
    const display = @import("display.zig");
    if (!display.global_display_manager.initialized) {
        var gpa = std.heap.GeneralPurposeAllocator(.{}){};
        const allocator = gpa.allocator();
        defer _ = gpa.deinit();
        
        display.global_display_manager = display.DisplayManager.init(allocator) catch return false;
        return true;
    }
    return true;
}

// API函数：获取显示设备数量
export fn exokernel_display_get_device_count() u32 {
    const display = @import("display.zig");
    if (!display.global_display_manager.initialized) {
        return 0;
    }
    return @as(u32, @intCast(display.global_display_manager.devices.items.len));
}

// API函数：获取显示设备ID
export fn exokernel_display_get_device_id(index: u32) DisplayDeviceId {
    const display = @import("display.zig");
    if (!display.global_display_manager.initialized or index >= display.global_display_manager.devices.items.len) {
        return 0;
    }
    return display.global_display_manager.devices.items[index].id;
}

// API函数：设置显示模式
export fn exokernel_display_set_mode(
    cap_id: CapabilityId,
    device_id: DisplayDeviceId,
    mode_index: u32
) bool {
    const display = @import("display.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .io, .write)) {
        return false;
    }
    return display.global_display_manager.setDisplayMode(device_id, mode_index);
}

// API函数：获取显示模式数量
export fn exokernel_display_get_mode_count(
    device_id: DisplayDeviceId
) u32 {
    const display = @import("display.zig");
    if (!display.global_display_manager.initialized) {
        return 0;
    }
    const device = display.global_display_manager.getDevice(device_id);
    if (device == null) {
        return 0;
    }
    return @as(u32, @intCast(device.?.modes.items.len));
}

// API函数：获取显示模式
export fn exokernel_display_get_mode(
    device_id: DisplayDeviceId,
    mode_index: u32,
    out_mode: *DisplayMode
) bool {
    const display = @import("display.zig");
    if (!display.global_display_manager.initialized) {
        return false;
    }
    const device = display.global_display_manager.getDevice(device_id);
    if (device == null or mode_index >= device.?.modes.items.len) {
        return false;
    }
    const display_mode = device.?.modes.items[mode_index];
    out_mode.* = DisplayMode{
        .width = display_mode.width,
        .height = display_mode.height,
        .refresh_rate = display_mode.refresh_rate,
        .pixel_format = display_mode.pixel_format,
        .pitch = display_mode.pitch,
    };
    return true;
}

// API函数：将缓冲区提交到显示设备
export fn exokernel_display_present_buffer(
    cap_id: CapabilityId,
    device_id: DisplayDeviceId,
    buffer_id: GpuResourceId
) bool {
    const display = @import("display.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .io, .write)) {
        return false;
    }
    return display.global_display_manager.presentBuffer(device_id, buffer_id);
}

// API函数：设置主显示设备
export fn exokernel_display_set_primary_device(
    cap_id: CapabilityId,
    device_id: DisplayDeviceId
) bool {
    const display = @import("display.zig");
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .io, .write)) {
        return false;
    }
    return display.global_display_manager.setPrimaryDevice(device_id);
}

// UI通信相关API函数
// 这些函数需要包含在api.zig中

// UI通信通道ID
pub const UICommChannelId = u64;

// UI消息ID
pub const UIMessageId = u64;

// UI资源ID
pub const UIResourceId = u64;

// UI事件类型常量
pub const UI_EVENT_MOUSE_MOVE = 1;
pub const UI_EVENT_MOUSE_CLICK = 2;
pub const UI_EVENT_KEY_PRESS = 3;
pub const UI_EVENT_KEY_RELEASE = 4;
pub const UI_EVENT_TOUCH_EVENT = 5;
pub const UI_EVENT_WINDOW_RESIZE = 6;
pub const UI_EVENT_WINDOW_MOVE = 7;

// UI命令类型常量
pub const UI_COMMAND_DRAW_RECT = 1;
pub const UI_COMMAND_DRAW_TEXT = 2;
pub const UI_COMMAND_DRAW_IMAGE = 3;
pub const UI_COMMAND_CLEAR_SCREEN = 4;
pub const UI_COMMAND_UPDATE_VIEW = 5;
pub const UI_COMMAND_CREATE_WINDOW = 6;

// UI消息结构体
pub const UIMessage = struct {
    id: UIMessageId,
    type: u32, // 事件或命令类型
    sender_id: u64,
    target_id: u64,
    size: u64,
    timestamp: u64,
    data: [*]u8,
};

// UI通信通道配置 - 使用 ui_comm.zig 中的定义
pub const UIChannelConfig = @import("ui_comm.zig").UIChannelConfig;

// API函数：初始化UI通信管理器
export fn exokernel_ui_comm_init() bool {
    const ui_comm = @import("ui_comm.zig");
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();
    
    ui_comm.initGlobalUICommManager(allocator) catch return false;
    return true;
}

// API函数：创建UI通信通道
export fn exokernel_ui_comm_create_channel(
    cap_id: CapabilityId,
    name_ptr: [*]const u8,
    name_len: u32,
    config: UIChannelConfig
) UICommChannelId {
    const ui_comm = @import("ui_comm.zig");
    const name = name_ptr[0..name_len];
    
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return 0;
    }
    
    return ui_comm.getGlobalUICommManager().createChannel(name, config, cap_id) catch 0;
}

// API函数：发送UI消息
export fn exokernel_ui_comm_send_message(
    cap_id: CapabilityId,
    channel_id: UICommChannelId,
    message_type: u32,
    sender_id: u64,
    target_id: u64,
    data_ptr: [*]const u8,
    data_len: u64
) UIMessageId {
    const ui_comm = @import("ui_comm.zig");
    const data = data_ptr[0..data_len];
    
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return 0;
    }
    
    return ui_comm.getGlobalUICommManager().sendMessage(channel_id, message_type, sender_id, target_id, data) catch 0;
}

// API函数：接收UI消息
export fn exokernel_ui_comm_receive_message(
    cap_id: CapabilityId,
    channel_id: UICommChannelId,
    buffer_ptr: [*]u8,
    buffer_len: u64,
    out_message: *UIMessage
) bool {
    const ui_comm = @import("ui_comm.zig");
    const buffer = buffer_ptr[0..buffer_len];
    
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .read)) {
        return false;
    }
    
    const message = ui_comm.getGlobalUICommManager().receiveMessage(channel_id, buffer) catch return false;
    out_message.* = .{
        .id = message.id,
        .type = message.type,
        .sender_id = message.sender_id,
        .target_id = message.target_id,
        .size = message.size,
        .timestamp = message.timestamp,
        .data = message.data,
    };
    return true;
}

// API函数：关闭UI通信通道
export fn exokernel_ui_comm_close_channel(
    cap_id: CapabilityId,
    channel_id: UICommChannelId
) bool {
    const ui_comm = @import("ui_comm.zig");
    
    if (!caps.global_capability_manager.checkCapabilityPermission(cap_id, .memory, .write)) {
        return false;
    }
    
    ui_comm.getGlobalUICommManager().closeChannel(channel_id) catch return false;
    return true;
}

// API函数：通过名称查找UI通信通道
export fn exokernel_ui_comm_find_channel_by_name(
    name_ptr: [*]const u8,
    name_len: u32
) UICommChannelId {
    const ui_comm = @import("ui_comm.zig");
    const name = name_ptr[0..name_len];
    
    if (ui_comm.getGlobalUICommManager().findChannelByName(name)) |_| {
        // 实际实现中需要返回通道ID
        // 这里只是一个示例
        return ui_comm.getGlobalUICommManager().name_to_id.get(name) orelse 0;
    }
    return 0;
}

// API函数：获取UI通信通道统计信息
export fn exokernel_ui_comm_get_channel_stats(
    channel_id: UICommChannelId,
    out_message_count: *u32,
    out_used_memory: *u64
) bool {
    const ui_comm = @import("ui_comm.zig");
    
    if (ui_comm.getGlobalUICommManager().getChannelStats(channel_id)) |stats| {
        out_message_count.* = stats.message_count;
        out_used_memory.* = stats.used_memory;
        return true;
    }
    return false;
}